// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ValueExpiry.cs" company="XamlNinja">
//   2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
// </summary>
// <credits>
// StuartHarris http://red-badger.com/Blog/post/Watching-Silverlight-Dependency-Properties-with-Reactive-Extensions.aspx#comment
// </credits>
// --------------------------------------------------------------------------------------------------------------------

namespace WP7Contrib.View.Controls.BindingListener
{
    using System;
    using System.Reactive.Linq;
    using System.Windows;
    using System.Windows.Data;

    public static class FrameworkElementExtensions
    {
        public static IObservable<ValueChangedEventArgs> GetChanges(this FrameworkElement element, Binding binding)
        {
            return Observable.Create<ValueChangedEventArgs>(
                observer =>
                    {
                        var listener = new DependencyPropertyListener();
                        return Observable.FromEventPattern<ValueChangedEventArgs>(
                            handler =>
                                {
                                    listener.ValueChanged += handler;
                                    listener.Attach(element, binding);
                                }, 
                            handler =>
                                {
                                    listener.ValueChanged -= handler;
                                    listener.Detach();
                                }).Select(@event => @event.EventArgs).Subscribe(observer);
                    });
        }
    }
}